<template>
  <div :class="$style['viewer-page']">
    <!-- 顶部工具栏 -->
    <header-toolbar
      :class="$style['viewer-header']"
      :patient-name="patientName"
      :patient-id="patientId"
      :active-study-id="activeStudyId"
      :study-list="studyList"
      @study-changed="loadStudy"
      @toggle-patient-info="showPatientInfo = !showPatientInfo"
      @go-back="goBack">
      
      <div :class="$style['header-left']" slot="left">
        <div :class="$style['tools-group']">
          <div :class="$style['tool-group']">
            <tool-button 
              icon="el-icon-search" 
              name="缩放" 
              :active="activeTool === 'Zoom'"
              @click="setActiveTool('Zoom')">
            </tool-button>
            
            <tool-button 
              icon="el-icon-attract" 
              name="平移" 
              :active="activeTool === 'Pan'"
              @click="setActiveTool('Pan')">
            </tool-button>
            
            <tool-button 
              icon="el-icon-rank" 
              name="窗宽窗位" 
              :active="activeTool === 'Wwwc'"
              @click="setActiveTool('Wwwc')">
            </tool-button>
          </div>
        </div>
      </div>
    </header-toolbar>
    
    <!-- 主要内容区域 -->
    <div :class="$style['viewer-content']" class="viewer-content">
      <!-- 序列面板 -->
      <series-panel
        :collapsed="seriesPanelCollapsed"
        :study-list="studyList"
        :active-study-id="activeStudyId"
        :active-series="activeSeries"
        :series-list="seriesList"
        @toggle="toggleSeriesPanel"
        @toggle-study="toggleStudy"
        @load-series="loadSeries">
      </series-panel>

      <!-- 医学影像查看区域 -->
      <div :class="$style['viewer-container']" :style="{
        marginLeft: seriesPanelCollapsed ? '30px' : '250px',
        marginRight: aiPanelCollapsed ? '30px' : '300px',
        transition: 'margin 0.3s ease'
      }">
        <div :class="$style['viewer-item']">
          <!-- Cornerstone 主视口 -->
          <cornerstone-viewer
            ref="cornerstoneViewer"
            :zoom-level="zoomLevel"
            :window-width="windowWidth"
            :window-center="windowCenter"
            :show-zoom-info="showZoomInfo"
            :show-wwwc-info="showWwwcInfo"
            @viewer-mounted="onViewerMounted"
            @mouse-down="handleMouseDown"
            @mouse-up="handleMouseUp"
            @mouse-move="handleMouseMove"
            @mouse-leave="handleMouseLeave"
            @mouse-wheel="handleMouseWheel"
            @context-menu="handleContextMenu">
            
            <!-- 将四角信息放置在插槽中 -->
            <corner-info 
              :class="[$style['corner-info'], $style['corner-info-tl']]" 
              slot="cornerTL"
              position="corner-info-tl">
              <div class="patient-info">
                <div>标识: {{ patientInfo ? patientInfo.ID : '-' }}</div>
                <div>姓名: {{ patientName }}</div>
                <div>检查号: {{ activeStudyId || '-' }}</div>
              </div>
              </corner-info>
            
            <corner-info 
              :class="[$style['corner-info'], $style['corner-info-tr']]" 
              slot="cornerTR"
              position="corner-info-tr">
              <div class="viewport-params">
                <div>W {{ windowWidth }} L {{ windowCenter }}</div>
                <div>缩放: {{ (zoomLevel * 100).toFixed(0) }}%</div>
              </div>
              </corner-info>
            
            <corner-info 
              :class="[$style['corner-info'], $style['corner-info-bl']]" 
              slot="cornerBL"
              position="corner-info-bl"
              v-if="currentImageIndex !== null">
              <div class="image-info">
                <div>Ser: {{ getActiveSeriesNumber() }}</div>
                <div>图像: {{ currentImageIndex + 1 }}/{{ totalImages }}</div>
                <div>层厚: {{ getSliceThickness() }}</div>
              </div>
              </corner-info>
            
            <corner-info
              :class="[$style['corner-info'], $style['corner-info-br']]"
              slot="cornerBR"
              position="corner-info-br"
              v-if="activeSeries">
              {{ currentSeriesDescription }}
              </corner-info>
          </cornerstone-viewer>
          
          <!-- 图像导航滑块 -->
          <image-slider
            :class="$style['image-slider']"
            v-if="totalImages > 1"
            :min="0"
            :max="totalImages - 1"
            :step="1"
            :value="currentImageIndex"
            @input="displayImage"
            orientation="vertical">
            <div slot="label">
              {{ currentImageIndex + 1 }} / {{ totalImages }}
            </div>
          </image-slider>
              </div>
            </div>
      
      <!-- AI 面板 -->
      <ai-panel 
        :collapsed="aiPanelCollapsed"
        @toggle="toggleAiPanel">
      </ai-panel>
          </div>
          
    <!-- 患者信息浮层 -->
    <patient-info-overlay
      v-if="showPatientInfo"
      :patient="patient"
      @close="showPatientInfo = false">
    </patient-info-overlay>
    
    <!-- 错误对话框 -->
    <error-dialog
      :visible.sync="showErrorDialog"
      :message="errorMessage"
      @retry="retryLoading">
    </error-dialog>
  </div>
</template>

<script>
import orthancService from '@/services/orthanc'
import cornerstone from 'cornerstone-core'
import cornerstoneMath from 'cornerstone-math'
import cornerstoneTools from 'cornerstone-tools'
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'
import dicomParser from 'dicom-parser'
import Hammer from 'hammerjs'

// 导入 ToolButton 组件
import ToolButton from '@/components/ToolButton.vue'
import PanelToggle from '@/components/PanelToggle.vue'
import CornerInfo from '@/components/CornerInfo.vue'
import AiPanelToggle from '@/components/AiPanelToggle.vue'
import ErrorDialog from '@/components/ErrorDialog.vue'
import AiPanel from '@/components/AiPanel.vue'
import PatientInfoOverlay from '@/components/PatientInfoOverlay.vue'
import HeaderToolbar from '@/components/HeaderToolbar.vue'
import SeriesPanel from '@/components/SeriesPanel.vue'
import CornerstoneViewer from '@/components/CornerstoneViewer.vue'
import ImageSlider from '@/components/ImageSlider.vue'

// 导入服务
import * as viewerService from '@/services/viewerService'
import * as cornerstoneService from '@/services/cornerstoneService'
import * as interactionService from '@/services/interactionService'
import * as viewportService from '@/services/viewportService'
import * as uiStateService from '@/services/uiStateService'
import * as mouseInteractionService from '@/services/mouseInteractionService'
import * as metadataService from '@/services/metadataService'
import * as loadingService from '@/services/loadingService'

export default {
  name: 'ViewerPage',
  // 注册组件
  components: {
    ToolButton,
    PanelToggle,
    CornerInfo,
    AiPanelToggle,
    ErrorDialog,
    AiPanel,
    PatientInfoOverlay,
    HeaderToolbar,
    SeriesPanel,
    CornerstoneViewer,
    ImageSlider
  },
  props: {
    patientId: {
      type: String,
      required: true
    },
    studyId: {
      type: String,
      required: true
    },
    preloadStrategy: {
      type: String,
      default: 'auto'
    }
  },
  data() {
    return {
      loading: true,
      patientName: '加载中...',
      seriesList: [],
      activeSeries: null,
      imageIds: [],
      currentImageIndex: 0,
      totalImages: 0,
      viewportElement: null,
      activeTool: 'StackScroll',  // 默认选择滚动工具
      stack: null,
      loadedImages: 0,
      patientInfo: null,
      currentSeriesDescription: '',
      imageMetadata: null,
      isFullscreen: false,
      showErrorDialog: false,
      errorMessage: '',
      resizeObserver: null,
      preloadRange: 10, // 预加载前后10张图像
      windowWidth: 400,
      windowCenter: 40,
      annotations: [],
      showImageInfo: false,
      studyList: [],
      activeStudyId: '',
      studyMetadata: null,
      
      // 新增缩放相关状态
      zoomLevel: 1.0,
      showZoomInfo: false,
      
      // 新增UI状态
      showPatientInfo: false,
      aiPanelCollapsed: false,
      showWwwcInfo: false,
      
      // 添加鼠标交互相关状态
      sliderValue: 0,
      sliderDebounceTimer: null,
      
      // 新增序列面板相关状态
      seriesPanelCollapsed: false,
      
      // 缓存展开的检查状态
      expandedStudies: {},
      
      aiResults: [], // 添加 AI 分析结果数据
    }
  },
  
  computed: {
    loadingPercentage() {
      return Math.min(Math.round(this.loadedImages / Math.max(this.totalImages, 1) * 100), 100);
    },
    
    // 添加滑块位置计算属性
    sliderPositionStyle() {
      return {
        position: 'absolute',
        right: this.aiPanelCollapsed ? '35px' : '305px', // 紧贴AI面板左侧
        top: '50%',
        transform: 'translateY(-50%)',
        zIndex: '990' // 确保在AI面板下方，但在其他元素上方
      };
    }
  },
  
  watch: {
    // 监听当前图像变化，更新元数据
    currentImageIndex(newIndex) {
      this.updateImageMetadata(newIndex)
    },
    // 监听总图像数量变化，重置滑块范围
    totalImages(newTotal, oldTotal) {
      if (newTotal !== oldTotal && this.currentImageIndex >= newTotal) {
        // 如果当前索引超出新的范围，调整到有效范围内
        this.displayImage(newTotal - 1);
      }
    }
  },
  async mounted() {
    console.log('ViewerPage 组件挂载...')
    try {
      // 初始化 Cornerstone
      await this.initializeCornerstone()
      
      // 注意：我们不再直接调用initializeViewer和setupResizeObserver
      // 这些都会在CornerstoneViewer组件挂载后由onViewerMounted处理
      
      // 添加键盘快捷键
      this.setupKeyboardShortcuts()
      
      // 获取患者信息
      try {
        this.patientInfo = await orthancService.getPatientInfo(this.patientId)
        this.patientName = this.patientInfo.name || '未知患者'
      } catch (error) {
        console.error('获取患者信息失败:', error)
        this.patientName = '未知患者'
      }
      
      // 获取患者的所有检查
      await this.loadPatientStudies()
      
      // 默认选择滚动工具
      this.activeTool = 'StackScroll';
      
      // 设置全局鼠标事件监听
      const globalMouseHandlers = {
        mouseDown: this.handleGlobalMouseDown,
        mouseUp: this.handleGlobalMouseUp,
        mouseMove: this.handleGlobalMouseMove
      };
      
      this.removeGlobalMouseListeners = interactionService.setupGlobalMouseEvents(globalMouseHandlers);
    } catch (error) {
      console.error('初始化查看器失败:', error)
      this.errorMessage = error.message || '未知错误'
      this.showErrorDialog = true
      this.loading = false
    }
  },
  beforeDestroy() {
    // 使用cornerstoneService清理资源
    cornerstoneService.cleanupCornerstone(this.viewportElement, this.resizeObserver);
    
    // 移除键盘快捷键
    document.removeEventListener('keydown', this.handleKeyDown);
    
    // 移除全屏变化监听
    if (this.removeFullscreenListeners) {
      this.removeFullscreenListeners();
    }
    
    // 移除事件监听器
    window.removeEventListener('resize', this.handleResize);
    
    // 移除鼠标事件监听
    if (this.removeMouseListeners) {
      this.removeMouseListeners();
    }
    
    // 移除全局鼠标事件监听
    if (this.removeGlobalMouseListeners) {
      this.removeGlobalMouseListeners();
    } else {
    document.removeEventListener('mousedown', this.handleGlobalMouseDown);
    document.removeEventListener('mouseup', this.handleGlobalMouseUp);
    document.removeEventListener('mousemove', this.handleGlobalMouseMove);
    }
    
    // 清除缩放信息显示的定时器
    if (this.zoomInfoTimeout) {
      clearTimeout(this.zoomInfoTimeout);
      this.zoomInfoTimeout = null;
    }
    
    if (this.wwwcInfoTimeout) {
      clearTimeout(this.wwwcInfoTimeout);
      this.wwwcInfoTimeout = null;
    }
  },
  methods: {
    async initializeCornerstone() {
      console.log('初始化 Cornerstone 库...')
      
      try {
        // 使用cornerstoneService初始化Cornerstone
        const success = await cornerstoneService.initializeCornerstone();
        
        if (!success) {
          throw new Error('Cornerstone初始化失败');
        }
        
        // 注册模拟图像加载器
        cornerstoneService.registerMockImageLoader();
      
      console.log('Cornerstone 初始化完成')
        return true;
      } catch (error) {
        console.error('初始化 Cornerstone 失败:', error);
        return false;
      }
    },
    
    initializeViewer() {
      try {
        console.log('初始化 Cornerstone 查看器...');
        
        // 注意：我们不再直接访问DOM元素
        // 而是通过onViewerMounted方法获取引用
        
        console.log('Cornerstone 查看器初始化完成');
        return true;
      } catch (error) {
        console.error('初始化查看器失败:', error);
        return false;
      }
    },
    
    setupEventListeners() {
      // 监听图像渲染事件
      this.viewportElement.addEventListener('cornerstoneimagerendered', this.onImageRendered);
      
      // 使用interactionService监听全屏变化
      this.removeFullscreenListeners = interactionService.setupFullscreenListeners((isFullscreen) => {
        this.isFullscreen = isFullscreen;
        this.handleResize();
      });
      
      // 监听窗口大小变化
      window.addEventListener('resize', this.handleResize);
    },
    
    setupResizeObserver() {
      // 使用cornerstoneService设置ResizeObserver
      if (this.viewportElement) {
        this.resizeObserver = cornerstoneService.setupResizeObserver(this.viewportElement);
        if (!this.resizeObserver) {
          console.error('无法设置ResizeObserver');
        }
      } else {
        console.error('无法设置ResizeObserver: 视口元素未定义');
      }
    },
    
    setupKeyboardShortcuts() {
      // 使用interactionService设置键盘快捷键
      const callbacks = {
        previousImage: this.previousImage.bind(this),
        nextImage: this.nextImage.bind(this),
        adjustWindowLevel: this.adjustWindowLevel.bind(this),
        resetView: this.resetView.bind(this),
        toggleFullscreen: this.toggleFullscreen.bind(this)
      };
      
      // 自定义键盘事件处理函数
      this.handleKeyDown = (event) => {
        interactionService.handleKeyDown(event, this.viewportElement, callbacks);
      };
      
      // 添加键盘快捷键监听
      interactionService.setupKeyboardShortcuts(this.handleKeyDown);
    },
    
    handleResize() {
      // 调整视图大小
      if (this.viewportElement) {
        // 确保cornerstone元素已正确启用
        try {
          cornerstone.getEnabledElement(this.viewportElement);
        } catch (e) {
          // 如果未启用，先不执行resize
          return;
        }
        
        // 重置视图，确保图像能够正确适应viewport
        cornerstone.reset(this.viewportElement);
        
        // 调整cornerstone视图大小
        cornerstoneService.resizeViewer(this.viewportElement);
        
        // 如果当前有图像显示，重新显示当前图像确保它正确填充
        if (this.imageIds.length > 0 && this.currentImageIndex >= 0) {
          const imageId = this.imageIds[this.currentImageIndex];
          // 使用setTimeout确保resize后再重新显示图像
          setTimeout(() => {
            viewportService.displayImage(imageId, this.viewportElement);
          }, 10);
        }
        
        // 分发事件以便其他组件也可以响应大小变化
        this.$nextTick(() => {
          window.dispatchEvent(new Event('layout-changed'));
        });
      }
    },
    
    handleFullscreenChange() {
      // 使用interactionService处理全屏变化回调
      const isFullscreen = !!(
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement
      );
      
      // 更新全屏状态
      this.isFullscreen = isFullscreen;
      
      // 调整视图大小
      this.handleResize();
    },
    
    onImageRendered(event) {
      // 获取渲染的图像
      const viewport = cornerstone.getViewport(event.target)
      
      // 更新窗宽窗位值
      this.windowWidth = Math.round(viewport.voi.windowWidth)
      this.windowCenter = Math.round(viewport.voi.windowCenter)
      
      // 更新图像元数据
      this.updateImageMetadata(this.currentImageIndex)
    },
    
    adjustWindowLevel(widthDelta, centerDelta) {
      if (!this.viewportElement) return;
      
      // 使用cornerstoneService调整窗宽窗位
      const success = cornerstoneService.adjustWindowLevel(this.viewportElement, widthDelta, centerDelta);
      
      if (success) {
        // 显示窗宽窗位信息
        this.showWwwcInfo = true;
        
        // 清除之前的定时器
        if (this.wwwcInfoTimeout) {
          clearTimeout(this.wwwcInfoTimeout);
        }
        
        // 设置新的定时器，2秒后隐藏窗宽窗位信息
        this.wwwcInfoTimeout = setTimeout(() => {
          this.showWwwcInfo = false;
        }, 2000);
      }
    },
    
    // 使用loadingService加载患者的所有检查
    async loadPatientStudies() {
      const context = {
        setLoading: (loading) => this.loading = loading,
        setStudyList: (studyList) => this.studyList = studyList,
        setActiveStudyId: (activeStudyId) => this.activeStudyId = activeStudyId,
        loadStudy: this.loadStudy.bind(this),
        setError: (error) => {
          this.errorMessage = error;
          this.showErrorDialog = true;
        }
      };
      
      return loadingService.loadPatientStudies(this.patientId, context);
    },
    
    // 使用loadingService加载检查
    async loadStudy(studyId) {
      const context = {
        setLoading: (loading) => this.loading = loading,
        resetData: () => {
        // 清空当前序列和图像
          this.seriesList = [];
          this.activeSeries = null;
          this.imageIds = [];
          this.currentImageIndex = 0;
          this.totalImages = 0;
        },
        setActiveStudyId: (activeStudyId) => this.activeStudyId = activeStudyId,
        setSeriesList: (seriesList) => this.seriesList = seriesList,
        setActiveSeries: (activeSeries) => this.activeSeries = activeSeries,
        loadSeries: this.loadSeries.bind(this),
        setError: (error) => {
          this.errorMessage = error;
          this.showErrorDialog = true;
        }
      };
      
      return loadingService.loadStudy(studyId, context);
    },
    
    // 使用loadingService加载序列
    async loadSeries(seriesId) {
      // 更新活动序列
      this.activeSeries = seriesId;
      
      // 找到对应的序列
      const series = this.seriesList.find(s => s.id === seriesId);
      if (!series) return false;
      
      // 添加调试信息
      console.log('开始加载序列:', seriesId, series);
      
      const context = {
        setActiveSeries: (activeSeries) => this.activeSeries = activeSeries,
        setSeriesLoading: (series, loading) => {
          this.$set(series, 'loading', loading);
          console.log(`设置序列 ${series.id} 加载状态:`, loading);
        },
        setImageIds: (imageIds) => this.imageIds = imageIds,
        setTotalImages: (totalImages) => this.totalImages = totalImages,
        setCurrentImageIndex: (index) => this.currentImageIndex = index,
        setSeriesDescription: (description) => this.currentSeriesDescription = description,
        loadAndDisplayImage: this.loadAndDisplayImage.bind(this),
        createThumbnail: (series, image) => {
          console.log('尝试为序列创建缩略图:', series.id);
          const success = viewerService.createThumbnail(series, image);
          if (success) {
            // 强制更新以确保UI显示缩略图
            this.$forceUpdate();
          }
          return success;
        },
        createPlaceholderThumbnail: (series) => {
          console.log('为序列创建占位缩略图:', series.id);
          // 创建占位缩略图
          const canvas = document.createElement('canvas');
          canvas.width = 60;
          canvas.height = 60;
          const ctx = canvas.getContext('2d');
          viewerService.createPlaceholderThumbnail(ctx, series);
          
          // 尝试将画布转换为URL
          try {
            const thumbnailUrl = canvas.toDataURL('image/jpeg', 0.8);
            this.$set(series, 'thumbnailUrl', thumbnailUrl);
            
            // 强制更新以确保UI显示缩略图
            this.$forceUpdate();
          } catch (e) {
            console.error('无法创建缩略图数据URL:', e);
          }
        },
        preloadImagesWithProgress: (imageIds, series) => {
          viewerService.preloadImagesWithProgress(imageIds, series);
        },
        setError: (error) => {
          this.errorMessage = error;
          this.showErrorDialog = true;
        }
      };
      
      return loadingService.loadSeries(seriesId, series, context);
    },
    
    // 使用loadingService加载并显示图像
    async loadAndDisplayImage(imageId) {
      if (!imageId) return null;
      
      const context = {
        currentImageIndex: this.currentImageIndex,
        updateImageMetadata: this.updateImageMetadata.bind(this)
      };
      
      return loadingService.loadAndDisplayImage(imageId, this.viewportElement, context);
    },
    
    async displayImage(imageIndex) {
      const context = {
        imageIds: this.imageIds,
        viewportElement: this.viewportElement,
        updateImageMetadata: this.updateImageMetadata.bind(this),
        setCurrentImageIndex: (index) => this.currentImageIndex = index,
        imageLoading: this.imageLoading,
        _lastRequestedIndex: this._lastRequestedIndex,
        preloadAdjacentImages: (index, imageIds) => viewerService.preloadAdjacentImages(index, imageIds)
      };
      
      return loadingService.displayImage(imageIndex, context);
    },
    
    // 使用viewerService更新图像元数据
    updateImageMetadata(index) {
      const metadata = viewerService.updateImageMetadata(index, this.imageIds, this.viewportElement);
      this.imageMetadata = metadata;
    },
    
    handleScroll(event) {
      if (!this.scrollThrottled) {
        this.scrollThrottled = true;
        
        // 确定滚动方向
        const delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
        
        // 计算新的索引
        let newIndex = this.currentImageIndex;
        if (delta < 0) {
          newIndex = Math.min(this.imageIds.length - 1, newIndex + 1);
        } else {
          newIndex = Math.max(0, newIndex - 1);
        }
        
        // 如果索引变化了，显示新图像
        if (newIndex !== this.currentImageIndex) {
          this.displayImage(newIndex);
        }
        
        // 50ms后允许下一次滚动
        setTimeout(() => {
          this.scrollThrottled = false;
        }, 50);
      }
      
      // 阻止默认滚动行为
      event.preventDefault();
    },
    
    previousImage() {
      if (this.currentImageIndex > 0) {
        this.displayImage(this.currentImageIndex - 1);
      }
    },
    
    nextImage() {
      if (this.currentImageIndex < this.totalImages - 1) {
        this.displayImage(this.currentImageIndex + 1);
      }
    },
    
    resetView() {
      cornerstoneService.resetView(this.viewportElement);
    },
    
    toggleFullscreen() {
      const success = interactionService.toggleFullscreen(this.viewportElement, this.isFullscreen);
      
      if (success) {
        // 会通过全屏变化事件更新isFullscreen状态
        // 这里不需要直接更新
      } else {
        console.error('切换全屏失败，浏览器可能不支持全屏API');
      }
    },
    
    formatDate(dateStr) {
      return interactionService.formatDate(dateStr);
    },
    
    formatStudyDate(dateStr) {
      return interactionService.formatStudyDate(dateStr);
    },
    
    retryLoading() {
      this.showErrorDialog = false
      this.loading = true
      
      // 使用正确的方法名，而不是loadStudyData
      if (this.activeStudyId) {
        this.loadStudy(this.activeStudyId);
      } else {
        this.loadPatientStudies();
      }
    },
    
    // 使用viewerService.preloadImagesWithProgress方法替换原有方法
    preloadImagesWithProgress(imageIds, series) {
      viewerService.preloadImagesWithProgress(imageIds, series);
    },
    
    // 保留接口兼容性，内部使用viewerService实现
    preloadImages(imageIds) {
      if (!imageIds || imageIds.length === 0) return;
      
      // 创建一个模拟series对象，以便能够使用预加载进度
      const dummySeries = {
        loadProgress: 0,
        loading: true,
      };
      
      viewerService.preloadImagesWithProgress(imageIds, dummySeries);
    },
    
    // 添加鼠标滚动处理方法
    setupMouseEvents() {
      if (this.viewportElement) {
        // 使用interactionService设置事件监听
        const handlers = {
          mouseDown: this.handleMouseDown,
          mouseUp: this.handleMouseUp,
          mouseMove: this.handleMouseMove,
          mouseLeave: this.handleMouseLeave,
          mouseWheel: this.handleMouseWheel
        };
        
        this.removeMouseListeners = interactionService.setupMouseEvents(this.viewportElement, handlers);
      }
    },
    
    handleMouseDown(event) {
      const result = mouseInteractionService.handleMouseDown(event, {
        viewportElement: this.viewportElement,
        currentImageIndex: this.currentImageIndex
      });
    },
    
    handleMouseUp(event) {
      const result = mouseInteractionService.handleMouseUp(event, {
        viewportElement: this.viewportElement
      });
    },
    
    handleMouseMove(event) {
      const result = mouseInteractionService.handleMouseMove(event, {
        viewportElement: this.viewportElement,
        currentImageIndex: this.currentImageIndex,
        totalImages: this.totalImages
      }, (newIndex) => {
        // 回调函数，用于图像索引变化时
            this.displayImage(newIndex);
      });
      
      // 如果缩放级别变化，更新UI
      if (result.changes.zoomChanged) {
        this.zoomLevel = result.changes.zoomLevel;
        uiStateService.showZoomInfoTemporary();
        this.showZoomInfo = true;
      }
    },
    
    handleMouseLeave(event) {
      const result = mouseInteractionService.handleMouseLeave(event, {
        viewportElement: this.viewportElement
      });
    },
    
    handleSliderChange(value) {
      // 直接显示对应的图像
      this.displayImage(value);
    },
    
    addCornerstoneTools(element) {
      if (!element) {
        console.error('无法添加Cornerstone工具: 元素未定义');
        return;
      }
      
      try {
        // 使用cornerstoneService添加工具
        cornerstoneService.addCornerstoneTools(element, this.imageIds);
        
        // 监听图像渲染事件以更新缩放级别
        element.addEventListener('cornerstoneimagerendered', this.onImageRendered);
      } catch (error) {
        console.error('添加Cornerstone工具失败:', error);
      }
    },
    
    setActiveTool(toolName) {
      const element = this.viewportElement;
      if (!element) return;
        
      // 使用cornerstoneService设置活动工具
      const success = cornerstoneService.setActiveTool(element, toolName);
      
      if (success) {
      this.activeTool = toolName;
      }
    },
    
    // 处理鼠标右键点击
    handleContextMenu(event) {
      // 阻止默认的右键菜单
      event.preventDefault();
    },
    
    // 切换患者信息显示
    togglePatientInfo() {
      this.showPatientInfo = uiStateService.togglePatientInfo();
    },
    
    // 切换序列面板
    toggleSeriesPanel() {
      this.seriesPanelCollapsed = !this.seriesPanelCollapsed;
      
      // 更新视图布局
      this.$nextTick(() => {
        this.handleResize();
        // 触发布局变化事件
        window.dispatchEvent(new Event('layout-changed'));
      });
    },
    
    // 切换AI面板
    toggleAiPanel() {
      this.aiPanelCollapsed = !this.aiPanelCollapsed;
      
      // 更新视图布局
      this.$nextTick(() => {
        this.handleResize();
        // 触发布局变化事件
        window.dispatchEvent(new Event('layout-changed'));
      });
    },
    
    // 格式化序列标签
    formatSeriesLabel(series) {
      const description = series.MainDicomTags.SeriesDescription || '未命名序列';
      const number = series.MainDicomTags.SeriesNumber || '';
      return `${number} - ${description}`;
    },
    
    // 反转图像
    invertImage() {
      if (this.viewportElement) {
        cornerstoneService.invertImage(this.viewportElement);
      }
    },
    
    // 格式化出生日期
    formatBirthDate(birthDate) {
      return metadataService.formatDate(birthDate);
    },
    
    // 处理全局鼠标按下事件
    handleGlobalMouseDown(event) {
      const result = mouseInteractionService.handleGlobalMouseDown(event, this.viewportElement);
    },
    
    // 处理全局鼠标释放事件
    handleGlobalMouseUp(event) {
      const result = mouseInteractionService.handleGlobalMouseUp(event);
    },
    
    // 处理全局鼠标移动事件
    handleGlobalMouseMove(event) {
      const result = mouseInteractionService.handleGlobalMouseMove(event, {
        viewportElement: this.viewportElement
      }, (zoomLevel) => {
        // 回调函数，用于缩放级别变化时
        this.zoomLevel = zoomLevel;
        this.showZoomInfo = uiStateService.showZoomInfoTemporary();
      });
    },
    
    // 应用缩放
    applyZoom(scaleFactor) {
      if (!this.viewportElement) return;
      
      const result = mouseInteractionService.applyZoom(this.viewportElement, scaleFactor);
      
      if (result && result.success) {
      // 更新缩放级别
        this.zoomLevel = parseFloat(result.scale.toFixed(2));
      
      // 显示缩放信息
        this.showZoomInfo = uiStateService.showZoomInfoTemporary();
      }
    },
    
    /**
     * 格式化滑块提示
     * @param {number} value - 滑块值
     * @returns {string} 格式化后的文本
     */
    formatTooltip(value) {
      return `${value + 1} / ${this.totalImages}`;
    },
    
    /**
     * 处理滑块输入（拖动中）
     * @param {number} value - 滑块值
     */
    handleSliderInput(value) {
      // 直接更新图像，不使用防抖
      this.displayImage(value);
    },
    
    handleMouseWheel(event) {
      const result = mouseInteractionService.handleMouseWheel(event, {
        currentImageIndex: this.currentImageIndex,
        totalImages: this.totalImages
      }, (newIndex) => {
        // 回调函数，用于图像索引变化时
        this.displayImage(newIndex);
      });
    },
    
    // 新增方法：切换检查
    toggleStudy(studyId) {
      const result = uiStateService.toggleStudy(studyId, this.activeStudyId);
      
      // 更新展开状态
      this.$set(this.expandedStudies, studyId, result.expanded);
      
      // 如果需要激活，加载检查
      if (result.shouldActivate) {
        this.activeStudyId = studyId;
        this.loadStudy(studyId);
      }
    },
    
    onViewerMounted(element) {
      console.log('CornerstoneViewer已挂载，获取DOM引用');
      if (!element) {
        console.error('无法获取CornerstoneViewer组件的DOM引用');
        return;
      }
      
      // 保存DOM引用
      this.viewportElement = element;
      
      // 延时以确保DOM完全渲染
      setTimeout(() => {
        try {
          // 启用Cornerstone元素
          cornerstoneService.enableElement(element).then(success => {
            if (success) {
          // 再次延时以确保启用完成
          setTimeout(() => {
                // 调整视图大小确保填充
                cornerstoneService.resizeViewer(element);
                
            // 添加工具
            this.addCornerstoneTools(element);
            
            // 设置事件监听器
            this.setupEventListeners();
            
            // 设置大小变化观察器
            this.setupResizeObserver();
                
                // 强制再次调整大小以确保全屏展示
                window.dispatchEvent(new Event('resize'));
          }, 50);
            } else {
              throw new Error('启用Cornerstone元素失败');
            }
          });
        } catch (error) {
          console.error('初始化Cornerstone元素失败:', error);
          this.errorMessage = '初始化查看器失败: ' + (error.message || '未知错误');
          this.showErrorDialog = true;
        }
      }, 50);
    },
    
    /**
     * 返回上一页
     */
    goBack() {
      this.$router.push('/patients');
    },

    /**
     * 获取当前活动序列的编号
     * @returns {string} 序列编号
     */
    getActiveSeriesNumber() {
      if (!this.activeSeries || !this.seriesList) return 'x';
      
      const series = this.seriesList.find(s => s.id === this.activeSeries);
      if (series) {
        return series.number || 'x';
      }
      return 'x';
    },
    
    /**
     * 获取当前图像的层厚信息
     * @returns {string} 层厚信息
     */
    getSliceThickness() {
      if (!this.imageMetadata) return '1.00mm';
      
      // 从元数据中获取层厚信息
      const thickness = this.imageMetadata.thickness;
      if (thickness) {
        return `${parseFloat(thickness).toFixed(2)}mm`;
      }
      return '1.00mm';
    }
  }
}
</script>

<style module>
@import '../styles/viewerPage.module.css';
</style> 